import itchat
import pandas as pd
from pyecharts import Pie, Map, Style, Page, Bar
import requests
import re

class RobotController(object):

    def __init__(self):

        itchat.auto_login(hotReload=True)
        itchat.run()
        self.friends = itchat.get_friends()
        friends_info = dict(
            # 省份
            province=self.get_key_info(self.friends, "Province"),
            # 城市
            city=self.get_key_info(self.friends, "City"),
            # 昵称
            nickname=self.get_key_info(self.friends, "Nickname"),
            # 性别
            sex=self.get_key_info(self.friends, "Sex"),
            # 签名
            signature=self.get_key_info(self.friends, "Signature"),
            # 备注
            remarkname=self.get_key_info(self.friends, "RemarkName"),
            # 用户名拼音全拼
            pyquanpin=self.get_key_info(self.friends, "PYQuanPin"))


        # 根据key值得到对应的信息
    def get_key_info(self, friends_info, key):
        return list(map(lambda friend_info: friend_info.get(key), friends_info))

    # 性别分析
    def analysisSex(self):
        friends_info = self.friends
        df = pd.DataFrame(friends_info)
        temp = df.groupby('Sex')
        sex_count = temp['Sex'].count()
        temp = dict(zip(list(sex_count.index), list(sex_count)))

        data = {}
        data['保密'] = temp.pop(0)
        data['男'] = temp.pop(1)
        data['女'] = temp.pop(2)
        # 画图
        page = Page()
        attr, value = data.keys(), data.values()
        chart = Pie('微信好友性别比')
        chart.add('', attr, value, center=[50, 50],
                  redius=[30, 70], is_label_show=True, legend_orient='horizontal', legend_pos='center',
                  legend_top='bottom', is_area_show=True)
        page.add(chart)
        page.render('analysisSex.html')

    # 省份分析
    def analysisProvince(self):
        friends_info = self.friends
        df = pd.DataFrame(friends_info)
        province_count = df.groupby('Province', as_index=True)['Province'].count().sort_values()
        temp = list(map(lambda x: x if x != '' else '未知', list(province_count.index)))
        # 画图
        page = Page()
        style = Style(width=1100, height=600)
        style_middle = Style(width=900, height=500)
        attr, value = temp, list(province_count)
        chart1 = Map('好友分布(中国地图)', **style.init_style)
        chart1.add('', attr, value, is_label_show=True, is_visualmap=True, visual_text_color='#000')
        page.add(chart1)
        chart2 = Bar('好友分布柱状图', **style_middle.init_style)
        chart2.add('', attr, value, is_stack=True, is_convert=True,
                   label_pos='inside', is_legend_show=True, is_label_show=True)
        page.add(chart2)
        page.render('analysisProvince.html')
        itchat.send_file('analysisProvince.html', toUserName='filehelper')

    # 具体省份分析
    def analysisCity(self,province='贵州'):
        friends_info = self.friends
        df = pd.DataFrame(friends_info)
        temp1 = df.query('Province == "%s"' % province)
        city_count = temp1.groupby('City', as_index=True)['City'].count().sort_values()
        attr = list(map(lambda x: '%s市' % x if x != '' else '未知', list(city_count.index)))
        value = list(city_count)
        # itchat.send_file('analysisCity.html', toUserName='filehelper')


    @itchat.msg_register(itchat.content.TEXT)
    def parse(self, msg='Hi!'):
        # if re.findall('^@.*',msg='你好'):
        #     # todo:调用淘宝搜索。
        #     pass
        # else:
        result = chat(msg)
        # itchat.send_msg(result, toUserName='filehelper')


def chat(msg):
    chat_url = 'http://www.tuling123.com/openapi/api'
    data = {
        'key': '1107d5601866433dba9599fac1bc0083',  # 如果这个Tuling Key不能用，那就换一个
        'info': msg,  # 这是我们发出去的消息
        'userid': 'itbao-robot',  # 这里你想改什么都可以
    }
    # 我们通过如下命令发送一个post请求
    r = requests.post(chat_url, data=data).json()
    return r['text']